'use strict';

app.controller('projectCtrl', ['$scope', '$http', '$stateParams', '$rootScope', '$filter', '$location', '$timeout', '$modal', function ($scope, $http, $stateParams, $rootScope, $filter, $location, $timeout, $modal) {
    $rootScope.clean($scope.app);
    $scope.info = {
        projectList: [],
        projectArray: [],
        actionStatus: true,
        showPagination: false,
        pageIndex : 1
    };

    $scope.getProjectPlanInfo = function () {
        $scope.info.projectPlanInfo = {};
        $.ajax({
            type: "get",
            url: matrix_product_url + '/projectPlan/getProjectPlans?containFinished=Y&projectPlanId=' + $stateParams.id,
            async: false,
            success: function (data) {
                if (data.code == 0) {
                    $scope.info.projectPlanInfo = data.data[0];
                } else {
                    $rootScope.showMessage("error", "失败", data.msg);
                }
            }
        });
    }
    $scope.getProjectPlanInfo();

    $scope.app.page = {};
    setStorage('brdBackUrl', $location.url())

    $scope.dataType = [];
    $scope.info.selectReq = null;

    $scope.initTitle = function () {
        if ($scope.info.type == 'add') {
            $scope.info.title = "新增项目计划";
        } else if ($scope.info.type == 'edit') {
            $scope.info.title = "编辑项目计划";
        } else {
            $scope.info.title = "查看项目计划";
        }
    };

    //初始化header数据
    $scope.app.headerPanel.buttons = [];
    var cancel = {
        title: '返回', func: function () {
            $rootScope.backHistory();
        }
    }
    $scope.app.headerPanel.buttons.push(cancel);

    getProjectList();


    if (!$rootScope.isUserCanOperateByRole('pm')) {
        $scope.info.actionStatus = false;
    }

    $scope.setList = function() {
        var dataArray = [];
        angular.forEach($scope.info.projectList, function(data, index) {
            if(parseInt(($scope.info.pageIndex-1)+"1") <= (index+1) && (index+1) <= parseInt($scope.info.pageIndex+"0")) {
                dataArray.push(data);
            }
        });
        $scope.info.projectArray = dataArray;
    }

    //get project details
    function getProjectList() {
        if (!$stateParams.id) {
            $rootScope.showMessage("error", "失败", "id未定义！");
            return false;
        }
        if (!$scope.info.projectPlanInfo.uplanId) {
            $rootScope.showMessage("error", "失败", "项目计划没有生成对应的项目！");
            return false;
        }
        var url = beetle_plan_url + "/project_plan/getPlanProjectList?withIntPro=true&token_id=" + getTokenId() + "&plan_id=" + $scope.info.projectPlanInfo.uplanId;
        $http.get(url).success(function (data) {
            $scope.info.projectList = data.data;
            $scope.info.projectArray = data.data;
            $scope.info.showPagination = data.data.length > 10 ? true : false;
            $scope.totalItems = data.data.length;
            angular.forEach($scope.info.projectList, function (projects) {
                //set btn status
                if ((projects.isOnBeetle == '0' && projects.project_status != 'PRO_MERGED' && projects.package_type != 'maven_jar') || (projects.package_type == 'ad')) {
                    projects.editCurrentBtn = true;
                } else {
                    projects.editCurrentBtn = false;
                }
                if ($rootScope.isUserCanOperateByRole('pm', 'dev', 'qa') && projects.project_status != 'PRO_MERGED' && ((projects.isOnBeetle == '0' && projects.package_type != 'maven_jar') || (projects.package_type == 'ad'))) {
                    projects.editApplyBtn = true;
                } else {
                    projects.editApplyBtn = false;
                }
                if (projects.isOnBeetle == '0' && projects.package_type != 'maven_jar' && projects.project_status != 'PRO_MERGED') {
                    projects.checkoutBranch = true;
                } else {
                    projects.checkoutBranch = false;
                }
                projects.project_status = $rootScope.getStatusDesc(projects.project_status);
                projects.projectInfo = projects.project_name.split("_")[1];

                var branchTip = "<table class='table table-bordered table-condensed' style='background-color: #23527c;width: 170px;'>";
                branchTip += '<tr><td style="width: 50px;">当前分支:</td><td style="width: 120px;word-wrap: break-word;">' + projects.project_name + '</td></tr>';
                if (projects.svn_from != null) {
                    branchTip += '<tr><td style="width: 50px;">来源:</td><td style="width: 120px;word-wrap: break-word;">' + projects.svn_from + '</td></tr>';
                }
                if (projects.from_version != null) {
                    branchTip += '<tr><td style="width: 50px;">来源版本号:</td><td style="width: 120px;word-wrap: break-word;">' + projects.from_version + '</td></tr>';
                }
                if (projects.from_svn_version != null) {
                    branchTip += '<tr><td style="width: 50px;">来源svn号:</td><td style="width: 120px;word-wrap: break-word;">' + projects.from_svn_version + '</td></tr>';
                }
                branchTip += '</table>';

                projects.branchTip = branchTip;
                getProjectListOfEdition(projects);
            });
        }).error(function (result) {
            $rootScope.showMessage("error", "失败", result.message);
        });
    }

    //jump url
    $scope.toUrlClick = function (project) {
        window.open(beetle_ui_url + "#/menu/project/" + project.project_name);
    };

    //get project edition(版本)
    function getProjectListOfEdition(projects) {
        var url = beetle_plan_url + "/project/getProjectEditionList?token_id=" + getTokenId() + "&project_name=" + projects.project_name;
        $http.get(url).success(function (data) {
            projects.projectEditionList = data.data;
            angular.forEach(data.data, function (edition) {
                if (edition.editionNum == "default") {
                    projects.build_status = edition.showNum.split('(')[1].split(')')[0];
                }
            });
        }).error(function (result) {
            $rootScope.showMessage("error", "失败", result.message);
        });
    };

    //click btn for open modal
    $scope.openCreateProjectModal = function () {
        featureModal($scope.info.projectPlanInfo.uplanId);
    };

    function featureModal(planId) {
        var modalInstance = $modal.open({
            animation: true,
            templateUrl: getTemplateUrl("matrix/component/tpl/createProjectModal.html"),
            controller: "createProjectCtrl",
            keyboard: true,
            backdrop: true,
            resolve: {
                planId: function () {
                    return planId;
                }
            }
        });

        //点击modal新增后，把modal中的值传过来
        modalInstance.result.then(function (data) {
            saveModel();
        }, function (reason) {
            cancelModal(reason);
        });
    };

    $scope.openSwitchBranchModal = function (project) {
        switchBranchModal($scope.info.projectPlanInfo.uplanId, project.trunk_name);
    };

    function switchBranchModal(planId, trunkName) {
        var info = {};
        info.planId = planId;
        info.trunkName = trunkName;
        var modalInstance = $modal.open({
            animation: true,
            templateUrl: getTemplateUrl("matrix/component/tpl/switchBranchModal.html"),
            controller: "switchBranchCtrl",
            keyboard: true,
            backdrop: true,
            resolve: {
                info: function () {
                    return info;
                }
            }
        });

        //点击modal新增后，把modal中的值传过来
        modalInstance.result.then(function (data) {
            saveModel();
        }, function (reason) {
            cancelModal(reason);
        });
    }

    $scope.openEditionModel = function (type, project) {
        editionModel(type, project.project_name);
    };

    function editionModel(type, projectName) {
        if (projectName == null || projectName == '') {
            $rootScope.showMessage("error", "失败", "参数projectName错误！");
            return false;
        }
        if (type != "TEST" && type != "INTEGRATION") {
            $rootScope.showMessage("error", "失败", "参数type错误！");
            return false;
        }
        var info = {};
        info.projectName = projectName;
        info.type = type;
        var modalInstance = $modal.open({
            animation: true,
            templateUrl: getTemplateUrl("matrix/component/tpl/editionModal.html"),
            controller: "editionCtrl",
            keyboard: true,
            backdrop: true,
            resolve: {
                info: function () {
                    return info;
                }
            }
        });

        //点击modal新增后，把modal中的值传过来
        modalInstance.result.then(function (data) {
            saveModel();
        }, function (reason) {
            cancelModal(reason);
        });
    };

    function saveModel() {
        getProjectList();
    };

    //close modal
    function cancelModal(reason) {
        console.log("cancel");
    };


    //remove project
    $scope.deleteProject = function (project) {
        //判断工程是否为集成计划的主干分支，如果是主干分支，不允许在页面操作删除
        if (project.plan_id != $scope.info.projectPlanInfo.uplanId) {
            $rootScope.showMessage("error", "失败", "集成计划主干分支不能删除,如果确定要删除,请联系系统管理员王健！");
            return false;
        }

        var confirmParams = {
            "titleData": "提示",
            "bodyData": "删除不可恢复，请确认！"
        };
        $rootScope.confirmWindow(confirmParams, function (val) {
            if(val) {
                var params = {
                    "titleData": "提示",
                    "bodyData": "是否要删除工程的svn目录？"
                };

                $scope.deletePro = function(flag) {
                    var url = beetle_plan_url + "/project_plan/delPlanProject?token_id=" + getTokenId() + "&trunk_name=" + project.trunk_name + "&plan_id=" + project.plan_id + "&is_del_svn=" + flag;
                    $http.get(url).success(function (data) {
                        if (data.success) {
                            getProjectList();
                        } else {
                            $rootScope.showMessage("error", "失败", data.msg);
                        }
                    });
                }

                var modalInstance = $modal.open({
                    animation: true,
                    templateUrl: 'confirmCtrl.html',
                    controller: 'confirmCtrl',
                    keyboard: false,
                    backdrop: 'static',
                    resolve: {
                        htmlEle: function () {
                            return params;
                        }
                    }
                });

                modalInstance.result.then(function (result) {
                        $scope.deletePro(false);
                    },
                    function (reason) {
                        $scope.deletePro(true);
                    });
            }
        });
    };
}]);